<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <el-form label-position="top" :model="userInfoForm" :rules="userInfoFormRules" ref="userInfoForm" @submit.native.prevent>
                <input type="hidden" value="userId" id="userId" v-model="userInfoForm.id">
                <el-form-item label="账号：" prop="accountName">
                    <el-input v-model="userInfoForm.accountName" auto-complete="off" placeholder="请输入账号"></el-input>
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="userInfoForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="职位：" prop="postName">
                    <el-input v-model="userInfoForm.postName" auto-complete="off" placeholder="请输入职位"></el-input>
                </el-form-item>
                <el-form-item label="用户所属组织/单位：" prop="selfOrgId">
                    <tree-select
                        v-model="userInfoForm.selfOrgId"
                        filterable
                        :width="536"
                        :data="orgList"
                        :defaultProps="orgDefaultProps"
                        :nodeKey="orgNodeKey"
                        :checkedKeys="checkedOrgKeys"
                        @popoverHide="orgPopoverHide">
                    </tree-select>
                </el-form-item>
                <el-form-item label="建筑物权限分配：" prop="buildIds" v-if="buildList.length > 0">
                    <tree-select
                        v-model="userInfoForm.buildIds"
                        filterable
                        :width="536"
                        :data="buildList"
                        :defaultProps="buildDefaultProps"
                        :checkedKeys="checkedBuildKeys"
                        :nodeKey="buildNodeKey">
                    </tree-select>
                </el-form-item>
                <el-form-item label="手机号：" prop='tel'>
                    <el-input v-model="userInfoForm.tel" auto-complete="off" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item class="multi-line" label="用户所属角色和管理的联网单位：">
                    <div class="multi-line-form" v-for="(item, i) in userRoleUnitList" :key="item.id">
                        <tree-select
                            v-model="item.roleId"
                            placeholder="请先选择角色"
                            filterable
                            :width="200"
                            :data="item.roleList"
                            :defaultProps="roleDefaultProps"
                            :checkedKeys="item.checkedRoleId"
                            :nodeKey="roleNodeKey"
                            :index="String(i)"
                            @popoverHide="rolePopoverHide">
                        </tree-select>
                        <tree-select
                            v-model="item.orgIds"
                            filterable
                            multiple
                            placeholder="请选择联网单位"
                            :width="200"
                            :data="item.orgList"
                            :defaultProps="orgDefaultProps"
                            :checkedKeys="item.checkedOrgIds"
                            :nodeKey="orgNodeKey">
                        </tree-select>
                    </div>
                    <div class="multi-line-button">
                        <el-button type="info" icon="el-icon-plus" circle size="small" @click="addMultiLineForm"></el-button>
                        <el-button type="info" icon="el-icon-delete" circle size="small" v-if="userRoleUnitList.length > 1" @click="deleteMultiLineForm"></el-button>
                    </div>
                </el-form-item>
                <el-form-item label-width="0" class="verifyidentity-button">
                    <el-button round @click="closeUserInfo">取消</el-button>
                    <el-button type="primary" round @click="addUser('userInfoForm')">确定</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import { getUcOrgList, getFbsTree, updateUserInfo, getRoleOrgByAccount, getRoleAuthList } from '@/api/sysConfig'
import { setTimeout } from 'timers';
import { validphone } from '@/utils/validate'

export default {
  name:'UserInfoMaintain',
  components: { 
    TreeSelect
  },
  props: {
    userInfo: {
      type: Object,
      required: false
    },
    orgList: {
      type: Array,
      required: true
    },
    roleList: {
      type: Array,
      required: true
    },
    closeUserInfo: {
        type: Function,
        required: true
    }
  },
  data() {
    const validatePhoneNum = (rule, value, callback) => {
        if(!validphone(value))
            callback(new Error('请输入正确的手机号'))
        callback()
    }
    return {
        orgDefaultProps: {
            children: 'nodes',
            label: 'name',
            value: 'id'
        },
        orgNodeKey: 'id',
        checkedOrgKeys: [], // 默认选中的
        buildList: [],
        buildDefaultProps: {
            children: 'nodes',
            label: 'text',
            value: 'id'
        },
        buildNodeKey: 'id',
        checkedBuildKeys: [], // 默认选中的
        userInfoForm: {
            id: '',
            accountName: '', // 账号
            name: '', // 姓名
            postName: '', // 职位
            selfOrgId: '', // 用户所属组织/单位
            buildIds: '', // 建筑物编号
            tel: ''
        },
        userInfoFormRules: {
            accountName: [
                { required: true, message: '请输入账号', trigger: 'blur' }
            ],
            name: [
                { required: true, message: '请输入姓名', trigger: 'blur' }
            ],
            selfOrgId: [
                { required: true, message: '请选择用户所属组织/单位', trigger: 'blur' }
            ],
            tel: [
                {  required: true,validator: validatePhoneNum  ,trigger: ['blur', 'change']}
            ],
            postName: [
                { required: true, message: '请输入职位', trigger: 'blur' }
            ]
        },
        roleDefaultProps: {
            children: 'nodes',
            label: 'name',
            value: 'id'
        },
        roleNodeKey: 'id',
        userRoleUnitList: [{
            id: '1',
            roleId: '',
            roleList: [],
            orgIds: '',
            orgList: [],
            checkedOrgIds: [], // 默认选中的值
            checkedRoleId: []  // 默认选中的值
        }], // 编辑时角色和联网单位关系
        multiLineNum: 1
    }
  },
  created() {
      let that = this
      let userInfoObj = this.userInfo
      if(userInfoObj.userId) {
          this.userInfoForm.id = userInfoObj.userId
          this.userInfoForm.accountName = userInfoObj.accountName
          this.userInfoForm.name = userInfoObj.name
          this.userInfoForm.postName = userInfoObj.postName
          this.userInfoForm.selfOrgId = userInfoObj.organizationId
          this.userInfoForm.buildIds = userInfoObj.buildIds
          this.userInfoForm.tel = userInfoObj.phone
          this.checkedOrgKeys = String(userInfoObj.organizationId).split(',')
          this.checkedBuildKeys = String(userInfoObj.buildIds).split(',')
          this.bindSelectFbs(userInfoObj.organizationId)
          this.echoRoleOrg(userInfoObj.accountName, userInfoObj.organizationId)
      } else {

      }
  },
  methods: {
    // 获取角色和联网单位关系
    setUserRoleUnitStr() {
        let arr = this.userRoleUnitList
        let newArr = []
        for (var i=0, len=arr.length; i < len; i++) {
            newArr.push({
                roleId: arr[i].roleId,
                orgIds: typeof(arr[i].orgIds) === 'string' ? arr[i].orgIds : arr[i].orgIds.join(',')
            })
        }
        return JSON.stringify(newArr)
    },
    // 增加新用户
    addUser(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        that.$refs[formName].validate((valid) => {
            if (valid) {
                let parames = that.userInfoForm
                // 组装角色和单位关系数据
                parames.userRoleUnitStr = that.setUserRoleUnitStr()
                // 提交
                updateUserInfo(parames).then(res => {
                    if(res.status === 200) {
                        that.$message({
                            message: '保存成功！',
                            type: 'success'
                        })
                        that.closeUserInfo(true)
                    } else {
                        that.$message({
                            message: res.info,
                            type: 'warning'
                        })
                    }
                });
            } else {
                return false
            }
        })
    },
    // 选择了用户所属组织/单位
    orgPopoverHide(checkedIds, checkedData) {
        // 用户所属组织选择值变化
        if(checkedIds && checkedIds !== this.userInfoForm.selfOrgId) {
            // 初始化建筑物值
            this.userInfoForm.buildIds = ''
            this.checkedBuildKeys = []
            // 重新绑定建筑物下拉框数据
            this.bindSelectFbs(checkedIds)
            // 初始化多行表单
            this.userRoleUnitList = []
            this.multiLineNum = 0
            this.addMultiLineForm()
        }
    },
    // 查询消防建筑物结构树
    bindSelectFbs(checkedIds) {
        var that = this
        if(checkedIds) {
            getFbsTree({
                organizationId: checkedIds
            }).then(res => {
                // var res = {"status":200,"info":"操作成功","total":1,"data":[{"indoorId":"","nodes":[{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308096109.png","isAddLayeredGraph":1,"id":519,"sort":0,"text":"东一层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308243087.png","isAddLayeredGraph":1,"id":520,"sort":0,"text":"一中庭","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308407201.png","isAddLayeredGraph":1,"id":522,"sort":0,"text":"西一层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308523671.png","isAddLayeredGraph":1,"id":523,"sort":0,"text":"东二层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308908170.png","isAddLayeredGraph":1,"id":524,"sort":0,"text":"西二层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517309564915.png","isAddLayeredGraph":1,"id":525,"sort":0,"text":"地下出口厅","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517309269772.png","isAddLayeredGraph":1,"id":526,"sort":0,"text":"夹层","parentId":518,"tags":""}],"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517918087785.png","isAddLayeredGraph":0,"id":518,"sort":0,"text":"南京站北站房","parentId":0,"tags":""}]}
                if(res.status === 200 && res.data.length > 0) {
                    that.buildList = res.data
                } else {
                    that.buildList = []
                }
            })
        }
    },
    // 根据选择的组织单位获取角色信息
    /*
     * 【参数说明】
     *    orgId：用户所属组织/单位编码，作为查询参数
     *        i：当前操作的多行表单排序号，从0开始算
     *  isReset：是否为重置下拉框数据
     *     data：赋值数据
     */
    bindSelectRole(orgId, i, isReset, data) {
        let that = this
        getRoleAuthList({
            orgId: orgId || ''
        }).then(res => {
            if(isReset) {
                // 初始化角色选择框
                that.userRoleUnitList[i].roleList = res.data
                that.userRoleUnitList[i].roleId = ''
                that.userRoleUnitList[i].checkedRoleId = []
            } else {
                that.userRoleUnitList[i].roleList = res.data
                that.userRoleUnitList[i].roleId = data || ''
                setTimeout(() => {
                    that.userRoleUnitList[i].checkedRoleId = data ? String(data).split(',') : []
                })
            }
        })
    },
    // 根据选择的角色获取联网单位
    /*
     * 【参数说明】
     *   roleId：多行表单当前行选择的角色id，作为查询参数
     *    orgId：用户所属组织/单位编码，作为查询参数
     *        i：当前操作的多行表单排序号，从0开始算
     *  isReset：是否为重置下拉框数据
     *     data：赋值数据
     */
    bindSelectRoleOrg(roleId, orgId, i, isReset, data) {
        var that = this
        getUcOrgList({
            roleId: roleId,
            orgId: orgId
        }).then(res => {
            if(isReset) {
                // 初始化单位选择框
                that.userRoleUnitList[i].orgList = res.data
                that.userRoleUnitList[i].orgIds = ''
                that.userRoleUnitList[i].checkedOrgIds = []
            } else {
                that.userRoleUnitList[i].orgList = res.data
                that.userRoleUnitList[i].orgIds = data || ''
                setTimeout(() => {
                    that.userRoleUnitList[i].checkedOrgIds = data ? String(data).split(',') : []
                })
            }
        })
    },
    // 选择了角色
    rolePopoverHide(checkedIds, checkedData) {
        if(checkedIds && event.currentTarget.offsetParent) {
            let index = event.currentTarget.offsetParent.getAttribute('data-index') // 操作的多行表单对应序号

            // 角色选择值变化
            if(checkedIds && checkedIds != this.userRoleUnitList[index].roleId) {
                // 重新绑定建筑物下拉框数据
                this.bindSelectRoleOrg(checkedIds, this.userInfoForm.selfOrgId, index, true)
            }
        }
    },
    //编辑回显联网单位和角色
    echoRoleOrg(account,orgId) {
        var that = this
    	getRoleOrgByAccount({
    		account:account
        }).then(res => {
            let arr = res.data
            // 重置多行表单
            that.multiLineNum = 0
            that.userRoleUnitList = []
            for(var i=0, len=arr.length; i < len; i++) {
                // 添加一行数据
                that.addMultiLineForm(() => {
                    // 绑定角色下拉框数据，并赋值
                    that.bindSelectRole(orgId, i, false, arr[i].roleId)
                    // 绑定联网单位下拉框数据，并赋值
                    that.bindSelectRoleOrg(arr[i].roleId, orgId, i, false, arr[i].orgIds)
                })
                
            }
        })
    },
    // 增加一行角色和单位关系
    addMultiLineForm(callback) {
        this.multiLineNum += 1
        let newObj = {
            id: this.multiLineNum,
            orgIds: '',
            orgList: [],
            roleId: '',
            roleList: [],
            checkedOrgIds: [],
            checkedRoleId: []
        }
        this.userRoleUnitList.push(newObj)
        if(callback && typeof(callback) === 'function') {
            callback()
        } else {
            // 获取角色信息
            this.bindSelectRole('', (this.multiLineNum-1), true)
        }
    },
    // 删除一行角色和单位关系
    deleteMultiLineForm() {
        this.userRoleUnitList.pop()
        this.multiLineNum -= 1 
    }
  }
}
</script>